package cn.chiship.framework.third.biz.wxpub.controller;

import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.constants.CommonConstants;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.third.biz.all.entity.ThirdApplicationKeyConfig;
import cn.chiship.framework.third.biz.wxpub.service.WeixinService;
import cn.chiship.framework.third.core.common.ThirdUtil;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.annotation.Authorization;

import javax.annotation.Resource;

import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatUserService;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatUser;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatUserExample;
import cn.chiship.framework.third.biz.wxpub.pojo.dto.ThirdWechatUserDto;
import cn.chiship.sdk.third.core.model.WeiXinConfigModel;
import cn.chiship.sdk.third.service.WxPubService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 微信用户控制层 2022/6/18
 *
 * @author lijian
 */
@RestController
@Authorization
@RequestMapping("/thirdWechatUser")
@Api(tags = "微信用户")
public class ThirdWechatUserController extends BaseController<ThirdWechatUser, ThirdWechatUserExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatUserController.class);

    private static final String COUNT_STRING = "count";

    @Resource
    private ThirdWechatUserService thirdWechatUserService;

    @Resource
    private WeixinService weixinService;

    @Resource
    private GlobalCacheService globalCacheService;

    @Resource
    private WxPubService wxPubService;

    @Override
    public BaseService getService() {
        return thirdWechatUserService;
    }

    @SystemOptionAnnotation(describe = "微信用户分页")
    @ApiOperation(value = "微信用户分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class,
                    paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified",
                    dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "tagIdList", value = "用户标签", dataTypeClass = String.class, paramType = "query"),

    })
    @GetMapping(value = "/page")
    public ResponseEntity<BaseResult> page(
            @RequestParam(required = false, defaultValue = "", value = "keyword") String keyword,
            @RequestParam(required = false, defaultValue = "", value = "tagIdList") String tagIdList) {
        ThirdWechatUserExample thirdWechatUserExample = new ThirdWechatUserExample();
        // 创造条件
        ThirdWechatUserExample.Criteria thirdWechatUserCriteria = thirdWechatUserExample.createCriteria();
        thirdWechatUserCriteria.andIsDeletedEqualTo(BaseConstants.NO).andAppIdEqualTo(ThirdUtil.getAppId());
        if (!StringUtil.isNullOrEmpty(keyword)) {
            thirdWechatUserCriteria.andNickNameLike("%" + keyword + "%");
        }
        if (!StringUtil.isNullOrEmpty(tagIdList)) {
            BaseResult baseResult = wxPubService.config(globalCacheService.getWeiXinConfigByAppId(ThirdUtil.getAppId())).token()
                    .tagGetUser(tagIdList);
            if (!baseResult.isSuccess()) {
                return super.responseEntity(baseResult);
            }
            List<String> openIds = new ArrayList<>();
            JSONObject json = (JSONObject) baseResult.getData();
            if (json.getInteger(COUNT_STRING) > 0) {
                openIds = Arrays
                        .asList(json.getJSONObject("data").getJSONArray("openid").stream().toArray(String[]::new));
            } else {
                openIds.add("-1");
            }
            thirdWechatUserCriteria.andOpenIdIn(openIds);

        }

        return super.responseEntity(BaseResult.ok(super.page(thirdWechatUserExample)));
    }

    @SystemOptionAnnotation(describe = "微信用户列表数据")
    @ApiOperation(value = "微信用户列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "关键字", dataTypeClass = String.class, paramType = "query"),})
    @GetMapping(value = "/list")
    public ResponseEntity<BaseResult> list(
            @RequestParam(required = false, defaultValue = "", value = "keyword") String keyword) {
        ThirdWechatUserExample thirdWechatUserExample = new ThirdWechatUserExample();
        // 创造条件
        ThirdWechatUserExample.Criteria thirdWechatUserCriteria = thirdWechatUserExample.createCriteria();
        thirdWechatUserCriteria.andIsDeletedEqualTo(BaseConstants.NO).andAppIdEqualTo(ThirdUtil.getAppId());
        if (!StringUtil.isNullOrEmpty(keyword)) {
            thirdWechatUserCriteria.andNickNameLike("%" + keyword + "%");
        }
        return super.responseEntity(BaseResult.ok(super.list(thirdWechatUserExample)));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "更新微信用户")
    @ApiOperation(value = "更新微信用户")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path",
            required = true)})
    @PostMapping(value = "update/{id}")
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id,
                                             @RequestBody @Valid ThirdWechatUserDto thirdWechatUserDto) {
        ThirdWechatUser thirdWechatUser = new ThirdWechatUser();
        BeanUtils.copyProperties(thirdWechatUserDto, thirdWechatUser);
        return super.responseEntity(super.update(id, thirdWechatUser));
    }

    /**
     * 同步粉丝
     */
    @ApiOperation(value = "同步粉丝")
    @GetMapping(value = "synchronizationUser")
    public ResponseEntity<BaseResult> syncUser() {
        return super.responseEntity(thirdWechatUserService.syncUser());
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "删除微信用户")
    @ApiOperation(value = "删除微信用户")
    @PostMapping(value = "remove")
    public ResponseEntity<BaseResult> remove(@RequestBody(required = true) List<String> ids) {
        ThirdWechatUserExample thirdWechatUserExample = new ThirdWechatUserExample();
        thirdWechatUserExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(thirdWechatUserExample));
    }

}
